package com.agileboot.domain.airport.reform;

import com.agileboot.common.core.page.PageDTO;
import com.agileboot.domain.airport.inspection.db.SirInspectionEntity;
import com.agileboot.domain.airport.inspection.db.SirInspectionService;
import com.agileboot.domain.airport.inspectionCheck.db.SirInspectionCheckEntity;
import com.agileboot.domain.airport.inspectionCheck.db.SirInspectionCheckService;
import com.agileboot.domain.airport.reform.db.SirReformMainMapper;
import com.agileboot.domain.airport.reformDetail.db.SirReformDetailService;
import com.agileboot.domain.airport.report.db.SirReportEntity;
import com.agileboot.domain.airport.report.db.SirReportService;
import com.agileboot.domain.airport.selfcheck.db.SirSelfCheckEntity;
import com.agileboot.domain.airport.selfcheck.db.SirSelfCheckServiceImpl;
import com.agileboot.domain.common.command.BulkOperationCommand;
import com.agileboot.domain.airport.reform.command.AddReformMainCommand;
import com.agileboot.domain.airport.reform.command.UpdateReformMainCommand;
import com.agileboot.domain.airport.reform.db.SirReformMainEntity;
import com.agileboot.domain.airport.reform.db.SirReformMainService;
import com.agileboot.domain.airport.reform.dto.ReformMainDTO;
import com.agileboot.domain.airport.reform.model.ReformMainModel;
import com.agileboot.domain.airport.reform.model.ReformMainModelFactory;
import com.agileboot.domain.airport.reform.query.ReformMainQuery;
import com.agileboot.domain.airport.reformDetail.db.SirReformDetailEntity; // 导入 SirReformDetailEntity
import com.agileboot.domain.system.dept.db.SysDeptEntity;
import com.agileboot.domain.system.dept.db.SysDeptService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class ReformMainApplicationService {

    private final ReformMainModelFactory modelFactory;
    @Qualifier("sirReformMainServiceImpl")
    private final SirReformMainService reformService;
    private final SysDeptService sysDeptService;
    @Qualifier("sirReformDetailServiceImpl")
    private final SirReformDetailService reformDetailService; // 注入 SirReformDetailService
    @Qualifier("sirInspectionServiceImpl")
    private final SirInspectionService inspectionService;
    private final SirSelfCheckServiceImpl sirSelfCheckService;
    private final SirInspectionCheckService sirInspectionCheckService;
    private final SirReformDetailService sirReformDetailService;
    private final SirReportService sirReportService;



    public PageDTO<ReformMainDTO> getReformList(ReformMainQuery query) {
        Page<SirReformMainEntity> page = reformService.page(query.toPage(), query.toQueryWrapper());
        List<ReformMainDTO> records = convertEntitiesToDTOs(page.getRecords());
        return new PageDTO<>(records, page.getTotal());
    }

    public List<ReformMainDTO> getReformListAll(ReformMainQuery query) {
        List<SirReformMainEntity> all = reformService.list(query.toQueryWrapper());
        return convertEntitiesToDTOs(all);
    }

    public ReformMainDTO getReformInfo(Long id) {
        SirReformMainEntity entity = reformService.getById(id);
        return convertEntitiesToDTOs(Collections.singletonList(entity)).get(0);
    }

    private List<ReformMainDTO> convertEntitiesToDTOs(List<SirReformMainEntity> entities) {
        if (entities == null || entities.isEmpty()) {
            return Collections.emptyList();
        }

        Set<Long> deptIds = new HashSet<>();
        Set<Long> inspectionCheckIds = new HashSet<>();
        Set<Long> inspectionIds = new HashSet<>();
        Set<Long> selfcheckIds = new HashSet<>();
        Set<Long> relatedQuestionIds = new HashSet<>();

        for (SirReformMainEntity entity : entities) {
            if (entity != null) {
                if (entity.getIssueDeptId() != null) {
                    deptIds.add(entity.getIssueDeptId());
                }
                if (entity.getDutyDeptId() != null) {
                    deptIds.add(entity.getDutyDeptId());
                }
                // MODIFICATION START: Add curDealDeptId to the set
                if (entity.getCurDealDeptId() != null) {
                    deptIds.add(entity.getCurDealDeptId());
                }
                // MODIFICATION END
                if (entity.getInspectionCheckId() != null) {
                    inspectionCheckIds.add(entity.getInspectionCheckId());
                }
                // 过滤无效的relatedQuestionId（排除null和<=0的值）
                if (entity.getRelatedQuestionId() != null && entity.getRelatedQuestionId() > 0) {
                    relatedQuestionIds.add(entity.getRelatedQuestionId());
                }
            }
        }

        List<SirInspectionCheckEntity> inspectionCheckEntities = inspectionCheckIds.isEmpty()
                ? Collections.emptyList()
                : sirInspectionCheckService.getByIds(inspectionCheckIds);

        if (inspectionCheckEntities != null) {
            for (SirInspectionCheckEntity check : inspectionCheckEntities) {
                if (check != null) {
                    if (check.getInspectionId() != null) {
                        inspectionIds.add(check.getInspectionId());
                    }
                    if (check.getSelfcheckId() != null) {
                        selfcheckIds.add(check.getSelfcheckId());
                    }
                }
            }
        }

        List<SirSelfCheckEntity> selfCheckEntities = selfcheckIds.isEmpty()
                ? Collections.emptyList()
                : sirSelfCheckService.getByIds(new ArrayList<>(selfcheckIds));

        Map<Long, SirSelfCheckEntity> selfCheckMap = selfCheckEntities != null
                ? selfCheckEntities.stream()
                .filter(Objects::nonNull)
                .collect(Collectors.toMap(SirSelfCheckEntity::getId, selfCheck -> selfCheck))
                : new HashMap<>();

        List<SirInspectionEntity> inspectionEntities = inspectionIds.isEmpty()
                ? Collections.emptyList()
                : inspectionService.getByIds(new ArrayList<>(inspectionIds));

        List<SirReportEntity> reportEntities = relatedQuestionIds.isEmpty()
                ? Collections.emptyList()
                : sirReportService.listByIds(relatedQuestionIds);

        Map<Long, SirInspectionEntity> inspectionMap = inspectionEntities != null
                ? inspectionEntities.stream()
                .filter(Objects::nonNull)
                .collect(Collectors.toMap(SirInspectionEntity::getInspectionId, inspection -> inspection))
                : new HashMap<>();

        Map<Long, SirInspectionCheckEntity> inspectionCheckMap = inspectionCheckEntities != null
                ? inspectionCheckEntities.stream()
                .filter(Objects::nonNull)
                .collect(Collectors.toMap(SirInspectionCheckEntity::getInspectionCheckId, inspectionCheck -> inspectionCheck))
                : new HashMap<>();

        Map<Long, SirReportEntity> reportMap = reportEntities != null
                ? reportEntities.stream()
                .filter(Objects::nonNull)
                .collect(Collectors.toMap(SirReportEntity::getReportId, report -> report))
                : new HashMap<>();

        List<SysDeptEntity> deptEntities = deptIds.isEmpty()
                ? Collections.emptyList()
                : sysDeptService.getByDeptIds(new ArrayList<>(deptIds));

        Map<Long, String> deptMap = deptEntities != null
                ? deptEntities.stream()
                .filter(Objects::nonNull)
                .collect(Collectors.toMap(SysDeptEntity::getDeptId, SysDeptEntity::getDeptName))
                : new HashMap<>();

        return entities.stream()
                .filter(Objects::nonNull)
                .map(entity -> {
                    ReformMainDTO dto = new ReformMainDTO(entity);

                    // 督查部门
                    if (entity.getIssueDeptId() != null) {
                        dto.setIssueDeptName(deptMap.getOrDefault(entity.getIssueDeptId(), null));
                    }

                    // 责任部门
                    if (entity.getDutyDeptId() != null) {
                        dto.setDutyDeptName(deptMap.getOrDefault(entity.getDutyDeptId(), null));
                    }

                    // MODIFICATION START: Set curDealDeptName from the map
                    // 处理部门
                    if (entity.getCurDealDeptId() != null) {
                        dto.setCurDealDeptName(deptMap.getOrDefault(entity.getCurDealDeptId(), null));
                    }
                    // MODIFICATION END

                    // 新版数据处理
                    if (entity.getInspectionCheckId() != null) {
                        dto.setProblemDetail(entity.getReformTitle());

                        SirInspectionCheckEntity inspectionCheck = inspectionCheckMap.get(entity.getInspectionCheckId());
                        if (inspectionCheck != null) {
                            // 设置问题来源
                            if (inspectionCheck.getInspectionId() != null) {
                                SirInspectionEntity inspection = inspectionMap.get(inspectionCheck.getInspectionId());
                                if (inspection != null) {
                                    dto.setProblemSource(inspection.getInspectionName());
                                }
                            }

                            // 设置依据
                            if (inspectionCheck.getSelfcheckId() != null) {
                                SirSelfCheckEntity selfCheck = selfCheckMap.get(inspectionCheck.getSelfcheckId());
                                if (selfCheck != null) {
                                    dto.setBasis(selfCheck.getComplianceCriteria());
                                }
                            }

                            if (inspectionCheck.getTittle() != null) {
                                dto.setProblemTittle(inspectionCheck.getTittle());
                            }
                        }

                        // 旧版数据处理
                    } else {
                        // 相关问题
                        if (entity.getRelatedQuestionId() != null && entity.getRelatedQuestionId() != 0) {
                            SirReportEntity report = reportMap.get(entity.getRelatedQuestionId());
                            dto.setProblemTittle(report.getTitle());
                        }else {
                            dto.setProblemTittle(entity.getQuestionTitle());
                        }



                        dto.setProblemDetail(entity.getReformTitle());



                        String sourceName = entity.getQuestionSourceName();
                        if (sourceName != null) {
                            switch (sourceName) {
                                case "2":
                                    dto.setProblemSource("隐患排查");
                                    break;
                                case "3":
                                    dto.setProblemSource("安全质量检查");
                                    break;
                                case "7":
                                    dto.setProblemSource("安全预警");
                                    break;
                                case "4":
                                    dto.setProblemSource("自愿上报");
                                    break;
                                default:
                                    dto.setProblemSource(entity.getQuestionTitle());
                                    break;
                            }
                        } else {
                            dto.setProblemSource(entity.getQuestionTitle());
                        }
                    }

                    return dto;
                })
                .collect(Collectors.toList());
    }

    public void addReform(AddReformMainCommand command) {
        // 生成 UUID 作为 reformId
        Long reformId = System.currentTimeMillis();
        command.setReformId(reformId); // 设置 reformId 到命令对象

        ReformMainModel model = modelFactory.create();
        command.setReformId(reformId); // 设置 reformId 到命令对象
        model.loadFromAddCommand(command);
        model.insert();

        // 创建 SirReformDetailEntity 并设置 reformId
        SirReformDetailEntity detailEntity = new SirReformDetailEntity();
        detailEntity.setCreateTime(new Date());
        detailEntity.setReformId(reformId);
        reformDetailService.save(detailEntity); // 插入 SirReformDetail 记录
    }

    public void updateReform(UpdateReformMainCommand command) {
        ReformMainModel model = modelFactory.loadById(command.getReformId());

        if(model.getReformStatus().equals("3") || model.getReformStatus().equals("5")|| model.getReformStatus().equals("1")){
            model.loadFromUpdateCommand(command);

        }
//        措施实施审核不通过
        else if (model.getReformStatus().equals("7") && command.getReformStatus().equals("6")) {
            model.loadFromUpdateCommand(command);
            if (command.getFinalResult().equals("2")){
                model.setActionIsOk("0");
                model.setCorrectiveActionProofEvalIsOk("0");
                model.setPrecautionActionProofEvalIsOk("1");
                sirReformDetailService.archiveProofByReformId(command.getReformId(),true,false);

            }else if (command.getFinalResult().equals("3")){
                model.setActionIsOk("0");
                model.setCorrectiveActionProofEvalIsOk("1");
                model.setPrecautionActionProofEvalIsOk("0");

                sirReformDetailService.archiveProofByReformId(command.getReformId(),false,true);

            }else if (command.getFinalResult().equals("4")){


                model.setActionIsOk("0");
                model.setCorrectiveActionProofEvalIsOk("0");
                model.setPrecautionActionProofEvalIsOk("0");
                sirReformDetailService.archiveProofByReformId(command.getReformId(),true,true);

            }

        }
        //整改措施实施通过
        else if (model.getReformStatus().equals("7") && command.getReformStatus().equals("4")) {
            model.loadFromUpdateCommand(command);
            model.setActionIsOk("1");
            model.setCorrectiveActionProofEvalIsOk("1");
            model.setPrecautionActionProofEvalIsOk("1");
            model.updateById();
            //如果这次是第一次提交整改
        }
        else if (model.getReformStatus().equals("2")) {
            model.loadFromUpdateCommand(command);

            // 根据reformId查询现有详情记录
            SirReformDetailEntity detailEntity = reformDetailService.getById(command.getReformId());

            // 如果不存在则创建新记录
            if (detailEntity == null) {
                detailEntity = new SirReformDetailEntity();
                detailEntity.setReformId(command.getReformId());
            }
            detailEntity.setCreateTime(new Date());

            if (command.getCorrectiveActionProof() != null){
                detailEntity.setCorrectiveActionProof(command.getCorrectiveActionProof());
                detailEntity.setOldCorrectiveActionProof(command.getCorrectiveActionProof());
                model.setCorrectiveActionProofEvalIsOk("1");
            }

            if (command.getPrecautionActionProof() != null){
                detailEntity.setPrecautionActionProof(command.getPrecautionActionProof());
                detailEntity.setOldPrecautionActionProof(command.getPrecautionActionProof());
                model.setPrecautionActionProofEvalIsOk("1");
            }


            reformDetailService.saveOrUpdate(detailEntity);

            // 检查两个证据字段是否均不为空且非空字节数组
            if ("1".equals(model.getCorrectiveActionProofEvalIsOk()) && "1".equals(model.getPrecautionActionProofEvalIsOk())) {
                model.setReformStatus("7"); // 设置整改状态为7
            }
        }
        //            重新提交整改
        else if(model.getReformStatus().equals("6")) {
            model.loadFromUpdateCommand(command);

            // 根据reformId查询现有详情记录
            SirReformDetailEntity detailEntity = reformDetailService.getById(command.getReformId());

            // 如果不存在则创建新记录
            if (detailEntity == null) {
                detailEntity = new SirReformDetailEntity();
                detailEntity.setReformId(command.getReformId());
            }
            detailEntity.setCreateTime(new Date());

            if (command.getSelectedProofType().equals("corrective")){
                detailEntity.setCorrectiveActionProof(
                        command.getCorrectiveActionProof() != null ?
                                command.getCorrectiveActionProof() : null
                );

                model.setCorrectiveActionProofEvalIsOk("1");
            } else {
                detailEntity.setPrecautionActionProof(
                        command.getPrecautionActionProof() != null ?
                                command.getPrecautionActionProof() : null
                );
                model.setPrecautionActionProofEvalIsOk("1");
            }

            reformDetailService.saveOrUpdate(detailEntity);


            if ("1".equals(model.getCorrectiveActionProofEvalIsOk()) && "1".equals(model.getPrecautionActionProofEvalIsOk())) {
                model.setReformStatus("7");
            }

        }

        model.updateById();
    }

    public void deleteReform(BulkOperationCommand<Long> deleteCommand) {
        reformService.removeBatchByIds(deleteCommand.getIds());
    }

    /**
     * 根据整改ID获取整改详情
     */
    public SirReformDetailEntity getReformDetail(Long reformId) {
        return reformDetailService.getById(reformId);
    }

}